package com.justonetech.translation.controller;

import com.justonetech.core.controller.BaseCRUDActionController;
import com.justonetech.core.orm.hibernate.Page;
import com.justonetech.core.orm.hibernate.QueryTranslate;
import com.justonetech.core.security.user.BaseUser;
import com.justonetech.core.security.util.SpringSecurityUtils;
import com.justonetech.core.utils.DateTimeHelper;
import com.justonetech.core.utils.FileUtils;
import com.justonetech.core.utils.ReflectionUtils;
import com.justonetech.translation.daoservice.DocAttachmentsService;
import com.justonetech.translation.daoservice.DocumentService;
import com.justonetech.translation.domain.DocAttachments;
import com.justonetech.translation.domain.Document;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @author: System
 */
@Controller
public class DocAttachmentsController extends BaseCRUDActionController<DocAttachments> {
    private static Log log = LogFactory.getLog(DocAttachmentsController.class);

    @Autowired
	private DocAttachmentsService docAttachmentsService;

    @Autowired
    private DocumentService documentService;

	@RequestMapping
    @ResponseBody
	public Page<DocAttachments> grid(Page page, String condition) {
		try {
            page.setAutoCount(true);

            String hql = "from DocAttachments t where 1=1 " + page.getOrderByString("t.treeId asc");

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);

            // 查询
            page = docAttachmentsService.findByPage(page, queryTranslate.toString());
		} catch (Exception e) {
            log.error("error", e);
		}

        return page;
	}

    @RequestMapping
    public String init(Model model, DocAttachments entity) throws Exception {
        try {
            if(entity != null && entity.getId() != null) {
                entity = docAttachmentsService.get(entity.getId());

                model.addAttribute("bean", entity);
            }
        } catch (Exception e) {
            log.error("error", e);
        }

        return "view/doc/docAttachmentsEdit";
    }

    @RequestMapping
    public String view(Model model, Long id) {
        DocAttachments docAttachments = docAttachmentsService.get(id);

        model.addAttribute("bean", docAttachments);
        return "view/doc/docAttachmentsView";
    }

    @RequestMapping
    public void save(HttpServletResponse response, Model model, @ModelAttribute("bean") DocAttachments entity)
            throws Exception {
        try {
            String[] columns = new String[]{
                    "id",
                    "doc",
                    "name",
                    "orginName",
                    "uploadDate",
                    "remark"
            };

            DocAttachments target;
            if (entity.getId() != null) {
                target = docAttachmentsService.get(entity.getId());

                ReflectionUtils.copyBean(entity, target, columns);
            } else {
                target = entity;
            }

            docAttachmentsService.save(target);
        } catch (Exception e) {
            log.error("error", e);
            super.processException(response, e);
        }

        sendSuccessJSON(response, "保存成功");
    }

    @RequestMapping
    public void delete(HttpServletResponse response, Long id) throws Exception {
        docAttachmentsService.delete(id);

        sendSuccessJSON(response, "删除成功");
    }

    /**
     * 初始化图片上传
     *
     * @param entity
     * @param result
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping
    public void upload(@ModelAttribute("page") DocAttachments entity,
                         BindingResult result, Model model, HttpServletRequest request,
                         HttpServletResponse response)
            throws Exception {
        try {
            BaseUser loginUser = SpringSecurityUtils.getCurrentUser();

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            Iterator it = multipartRequest.getFileNames();
            Document document = entity.getDoc();

            if(it.hasNext() && document == null) {
                document = new Document();

                documentService.save(document);
            }

            while (it.hasNext()) {
                String name = (String) it.next();

                CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest
                        .getFile(name);

                if (!FileUtils.isEmptyFile(orginalFile)) {
                    Map map = this.saveToDisk(orginalFile, request);

                    DocAttachments attachments = new DocAttachments();

                    attachments.setDoc(document);
                    attachments.setName((String) map.get("newFileName"));
                    attachments.setOrginName((String) map.get("fileName"));
                    attachments.setUploadDate(new Date(System.currentTimeMillis()));
                    attachments.setFilePath((String) map.get("filePath"));

                    docAttachmentsService.save(attachments);
                }
            }

            sendSuccessJSON(response, document.getId().toString());
        } catch (Exception e) {
            log.info("error", e);

            throw e;
        }
    }

    /**
     * 将文件保存到磁盘
     *
     * @param orginalFile
     * @param request
     * @return
     * @throws java.io.IOException
     */
    private Map saveToDisk(CommonsMultipartFile orginalFile,
                           HttpServletRequest request) throws Exception {

        DataOutputStream out = null;
        InputStream is = null;// 附件输入流

        try {
            String filePath = request.getRealPath("uploads") + File.separator;

            String dateStr = DateTimeHelper.dateToString("YYYYMMDD");

            File destinationDir = new File(filePath + dateStr);

            if (!destinationDir.exists()) {
                destinationDir.mkdirs();
            }

            HashMap result = new HashMap();

            if (orginalFile == null || orginalFile.isEmpty()) {// 空文件
                return result;
            }

            String fileName = FileUtils.extractFileName(orginalFile
                    .getFileItem().getName());

            String newFileName = System.currentTimeMillis() + "_" + fileName;

            File newFile = new File(destinationDir + File.separator
                    + newFileName);

            if (!newFile.exists()) {
                newFile.createNewFile();
            }

            out = new DataOutputStream(new FileOutputStream(newFile));// 存放文件的绝对路径

            is = orginalFile.getInputStream();
            byte[] b = new byte[is.available()];
            is.read(b);
            out.write(b);

            result.put("fileName", fileName);
            result.put("newFileName", newFileName);
            result.put("filePath", "/uploads/" + dateStr + "/");

            return result;
        } catch (IOException ie) {
            throw ie;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ie1) {
                    ie1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ie2) {
                    ie2.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载
     *
     * @param response
     * @param request
     * @param model
     * @param entity
     * @throws Exception
     */
    @RequestMapping
    public void download(HttpServletResponse response, HttpServletRequest request,
                         Model model, @ModelAttribute("bean") DocAttachments entity)
            throws Exception {
        try {
            DocAttachments bean = docAttachmentsService.get(entity.getId());

            if(bean != null && !bean.getDoc().getId().equals(entity.getDoc().getId())) {
                super.sendFailureJSON(response, "您所下载的文件不存在!");
                return;
            }

            String filePath = request.getRealPath("") + bean.getFilePath() + bean.getName();

            File file = new File(filePath);

            super.download(response, bean.getOrginName(), file);
        } catch (Exception e) {
            super.sendFailureJSON(response, "下载文件出错:" + ExceptionUtils.getRootCauseMessage(e));
        }
    }
}